package com.ruoyi.yipaiju.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.ruoyi.common.constant.BizConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.utils.CurrencyUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.common.utils.http.HttpRespons;
import com.ruoyi.yipaiju.service.ICommonService;
import org.springframework.stereotype.Service;

@Service
public class CommonServiceImpl implements ICommonService {
    @Override
    public ApiResult getAddress(String latitude, String longitude) {
        // 根据坐标获取省市区
        if (StringUtils.isNotEmpty(latitude) && StringUtils.isNotEmpty(longitude)){
            HttpRequest httpRequest = new HttpRequest();
            HttpRespons httpRespons = httpRequest.sendGet(String.format(BizConstants.GEOCODER_LOCATION_URL, latitude+","+longitude));
            if (httpRespons != null && httpRespons.getCode() == HttpStatus.SUCCESS){
                JSONObject resultJson = JSONObject.parseObject(httpRespons.getContent());
                int status = (int) CurrencyUtil.readJson(resultJson, "status");
                if (status == 0){
                    String province = String.valueOf(CurrencyUtil.readJson(resultJson, "result.address_component.province"));
                    String city = String.valueOf(CurrencyUtil.readJson(resultJson, "result.address_component.city"));
                    String district = String.valueOf(CurrencyUtil.readJson(resultJson, "result.address_component.district"));
                    return ApiResult.success(ImmutableMap.of("province", province, "city", city, "district", district));
//                return ApiResult.success(ImmutableMap.of("province", "广东省", "city", "深圳市", "district", ""));
                }
            }
        }
        return ApiResult.success(ImmutableMap.of("province", "", "city", "", "district", ""));
    }
}
